package com.ming.util;

import com.ming.exception.ParamException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

/**
 * 参数校验
 * @author MING
 * @date 2018/8/10 11:23
 */
public class BeanValidator {
    // Validator工厂 全局检验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * @param t
     * @param groups
     * @param <T> 类型
     * @return
     */
    public static <T> String validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return null;
        } else {
            String errors = "参数错误";
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                errors = violation.getMessage();
            }
            return errors;
        }
    }

    public static String validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return null;
        } else {
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        String str = BeanValidator.validateObject(param);
        if (str != null && !str.isEmpty()) {
            throw new ParamException(str);
        }
    }
}
